// import Footer from '@/components/Footer';
import { SettingDrawer } from '@ant-design/pro-layout';
import RightContent from '@/components/RightContent';
// import { BookOutlined, LinkOutlined } from '@ant-design/icons';
import type { Settings as LayoutSettings, BasicLayoutProps } from '@ant-design/pro-components';
import { PageLoading } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig, RequestConfig } from 'umi';
import { history, getLocale } from 'umi';
import { message } from 'antd';
import defaultSettings from '../config/defaultSettings';
import { TOKEN_NAME } from '@/utils/constant';
import { fetchUserInfo } from '@/models/userInfo';
import { fetchPermissions } from '@/models/menus';
import { stringify } from 'querystring';

const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';
const locale = getLocale();

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  permissions?: API.Permissions;
  loading?: boolean;
}> {
  // 如果不是登录页面，执行
  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    let permissions = {};
    if (currentUser) {
      const data = await fetchPermissions();
      permissions = data;
    }
    return {
      currentUser,
      permissions,
      settings: defaultSettings,
    };
  }
  return {
    settings: defaultSettings,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    // waterMarkProps: {
    //   content: initialState?.currentUser?.name,
    // },
    footerRender: null, //() => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    // links: isDev
    //   ? [
    //       <Link key="openapi" to="/umi/plugin/openapi" target="_blank">
    //         <LinkOutlined />
    //         <span>OpenAPI 文档</span>
    //       </Link>,
    //       <Link to="/~docs" key="docs">
    //         <BookOutlined />
    //         <span>业务组件文档</span>
    //       </Link>,
    //     ]
    //   : [],
    menuHeaderRender: undefined,
    childrenRender: (children: JSX.Element, props: BasicLayoutProps) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <>
          {children}
          {!props.location?.pathname?.includes('/login') && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};

export const request: RequestConfig = {
  prefix: isDev ? '/api' : 'https://tyapi.119.net',
  timeout: 10000,
  requestInterceptors: [
    // 请求拦截器，接收数组，可设置多个拦截器
    (_, options: any) => {
      return {
        options: {
          ...options,
          headers: {
            ...(options?.headers ?? {}),
            'ty-stoken': localStorage.getItem(TOKEN_NAME), // 这里获取自己的token携带在请求头上
          },
        },
      };
    },
  ],
  responseInterceptors: [
    async (response) => {
      if (response) {
        // if (response.status === 200) {
        const data = await response.clone().json();
        // 10011表示token失效
        if (data.code === 10011) {
          const {
            location: { search, pathname },
          } = history;
          if (pathname !== loginPath) {
            message.error(data.msg);
            history.replace({
              pathname: loginPath,
              search: stringify({
                redirect: pathname + search,
              }),
            });
          }
        } else if (data.code !== 0) {
          message.error(data.msg);
        }
        // }
      } else {
        message.error(locale === 'zh-CN' ? '网络异常' : 'Network error');
      }
      return response;
    },
  ],
  errorHandler: (error) => {
    const { response } = error;
    if (response && response.status) {
      message.error(response.statusText);
    }

    if (!response) {
      message.error(locale === 'zh-CN' ? '网络异常' : 'Network error');
    }
    throw error;
  },
};
